package com.lanproperiesinternal.util;

import com.alibaba.fastjson.JSON;
import com.lanproperiesinternal.config.OrderedProperties;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * @author kezhihui
 * @date 2022/05/16
 */
public class FileUtil {

    public static String getPropertiesFromFile(InputStream inputStream) throws IOException {
//        InputStream inputStream = new FileInputStream(file);
        ResourceBundle resourceBundle = new PropertyResourceBundle(inputStream);

        Enumeration<String> keys = resourceBundle.getKeys();
        TreeMap<String,String> res = new TreeMap();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String value = resourceBundle.getString(key);
            res.put(key,value);
            System.out.println(key + " = " + value);
        }
        return JSON.toJSONString(res);
    }

    /**
     * 将multipartFile转为file模式
     * @param multipartFile
     * @return
     */
    public static File multipartFileToFile(MultipartFile multipartFile) {
        String path = "tmp" + File.separator +UUID.randomUUID() + multipartFile.getOriginalFilename();
        //创建一个file对象
        File file = new File(path);
        //将multipartFile的输入流，拷贝到file对象，此时file对象的内容就是mutipartFile中的内容
        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 读Properties文件（有序）
     */
    public static OrderedProperties readOrderedPropertiesFile(MultipartFile multipartFile) {
        OrderedProperties properties = new OrderedProperties();
        InputStreamReader inputStreamReader = null;
        try {
//            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            InputStream inputStream = multipartFile.getInputStream();
            //prop.load(in);//直接这么写，如果properties文件中有汉子，则汉字会乱码。因为未设置编码格式。
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            properties.load(inputStreamReader);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
        return properties;
    }

    /**
     * 写Properties文件（有序）
     */
    public static void writeOrderedPropertiesFile(OrderedProperties properties,String fileName) {
        OutputStreamWriter outputStreamWriter = null;
        try {
            //保存属性到b.properties文件
            FileOutputStream fileOutputStream = new FileOutputStream(fileName, false);//true表示追加打开,false每次都是清空再重写
            outputStreamWriter = new OutputStreamWriter(fileOutputStream,"utf-8");
            // store方法存在！自动转义问题
            // properties.store(outputStreamWriter,null);
            Enumeration<?> e = properties.keys();
            while(e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = properties.getProperty(key);
                String s = key + "=" + value + "\n";
                outputStreamWriter.write(s);
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }

    }


    /**
     * 将properties的内容转化为json格式字符串
     */
    public static String printProp(Properties properties) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        for (String key : properties.stringPropertyNames()) {
            map.put(key,properties.getProperty(key));
        }
        String res = JSON.toJSONString(map);
        return res;
    }

    /**
     * 将properties的值返回
     */
    public static List getProValues(Properties properties) {
        ArrayList list = new ArrayList(properties.size());
        for (String key : properties.stringPropertyNames()) {
            list.add(properties.getProperty(key));
        }
        return list;
    }


}
